package com.ctl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctl.dto.CommentDTO;
import com.ctl.dto.CommentUserDTO;
import com.ctl.dto.VideoCommentDTO;
import com.ctl.entity.Comment;
import com.ctl.entity.User;
import com.ctl.feign.UserClient;
import com.ctl.service.CommentService;
import com.ctl.mapper.CommentMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author stars
* @description 针对表【comment(评论)】的数据库操作Service实现
* @createDate 2023-03-03 15:10:34
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{
    @Autowired
    private CommentMapper mapper;
    @Autowired
    private UserClient userClient;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public VideoCommentDTO videoCommentPage(Integer videoId, Integer page, Integer perPage) {
        //根据视频id获取 该视频评论列表  分页查询所有评论
        List<Comment> comments = mapper.getByVideoIdComment(videoId,(page-1)*perPage,perPage);
        VideoCommentDTO videoCommentDTO = new VideoCommentDTO();
        //获取该视频的 评论的总条数
        videoCommentDTO.setTotal_count(comments.size());
        //创建视频评论dto集合
        List<CommentDTO> commentDTOS=new ArrayList<>();
        for (Comment comment : comments) {
            //获取评论的用户信息
            User user = userClient.getUser(comment.getUid());
            CommentDTO commentDTO = new CommentDTO();
            CommentUserDTO userDTO = new CommentUserDTO();
            //父评论同等属性赋值
            BeanUtils.copyProperties(user,userDTO);
            commentDTO.setReviewer(userDTO);
            BeanUtils.copyProperties(comment,commentDTO);
            //处理子评论列表
            List<Comment> ziComments = comment.getComments();
            List<CommentDTO> zicommentDTOS=new ArrayList<>();
            for (Comment ziComment : ziComments) {
                //获取子评论用户信息
                User ziuser = userClient.getUser(ziComment.getUid());
                CommentDTO zicommentDTO = new CommentDTO();
                CommentUserDTO ziuserDTO = new CommentUserDTO();
                //子评论同等属性赋值
                BeanUtils.copyProperties(ziuser,ziuserDTO);
                zicommentDTO.setReviewer(ziuserDTO);
                BeanUtils.copyProperties(ziComment,zicommentDTO);
                zicommentDTOS.add(zicommentDTO);
            }
            commentDTO.setSub_comments(zicommentDTOS);
            commentDTOS.add(commentDTO);
        }
        videoCommentDTO.setItems(commentDTOS);
        return videoCommentDTO;
    }
}




